package service

import (
	"errors"
	"gin_server/internal/model"
	"gin_server/internal/repository"
	"gin_server/internal/request"
	"gin_server/pkg/crypto"
	"gin_server/pkg/jwt"
	"gin_server/pkg/utils"

	"gorm.io/gorm"
)

type LoginResponse struct {
	AccessToken  string `json:"access_token"`  // 访问令牌
	RefreshToken string `json:"refresh_token"` // 刷新令牌
	TokenType    string `json:"token_type"`    // 令牌类型，默认Bearer
}

// UserService 定义user服务接口
type UserService interface {
	// CreateUser 创建新user
	CreateUser(entity *model.User) (*model.User, error)

	// GetUserByID 根据ID获取user
	GetUserByID(id int64) (*model.User, error)

	// GetAllUser 获取所有user列表
	GetAllUser(params *request.UserQueryRequest) ([]*model.User, int64, error)

	// UpdateUser 更新user信息
	UpdateUser(id uint, entity *request.UserUpdateRequest) error

	// DeleteUser 软删除user
	DeleteUser(id uint) error

	// RestoreUser 恢复user
	RestoreUser(id uint) error

	// ForceDeleteUser 真删除user
	ForceDeleteUser(id uint) error

	// Register 用户注册
	Register(entity *request.RegisterRequest) (*model.User, error)

	// Login 用户登录
	Login(account, password string) (*LoginResponse, error)

	// RefreshToken 刷新token
	RefreshToken(refreshToken string) (*LoginResponse, error)
}

type userService struct {
	repository repository.UserRepository
}

func NewUserService(repo repository.UserRepository) UserService {
	return &userService{repository: repo}
}

func (s *userService) CreateUser(entity *model.User) (*model.User, error) {
	// 可以在这里添加业务校验逻辑
	// 对密码进行加密
	hashedPassword, err := crypto.HashPassword(entity.Password)
	if err != nil {
		return nil, err
	}
	entity.Password = hashedPassword
	return s.repository.Create(entity)
}

func (s *userService) GetUserByID(id int64) (*model.User, error) {
	return s.repository.FindByID(uint(id))
}

func (s *userService) GetAllUser(params *request.UserQueryRequest) ([]*model.User, int64, error) {
	return s.repository.FindAll(params)
}

func (s *userService) UpdateUser(id uint, entity *request.UserUpdateRequest) error {
	// 可以在这里添加业务校验逻辑
	return s.repository.Update(id, entity)
}

func (s *userService) DeleteUser(id uint) error {
	// 可以在这里添加业务校验逻辑
	return s.repository.Delete(id)
}

func (s *userService) RestoreUser(id uint) error {
	// 可以在这里添加业务校验逻辑
	return s.repository.Restore(id)
}

func (s *userService) ForceDeleteUser(id uint) error {
	return s.repository.ForceDelete(id)
}

// Register 用户注册
func (s *userService) Register(entity *request.RegisterRequest) (*model.User, error) {
	// 对密码进行加密
	hashedPassword, err := crypto.HashPassword(entity.Password)
	if err != nil {
		return nil, err
	}
	entity.Password = hashedPassword
	// 检查验证码是否正确
	emailService := NewEmailService()
	valid, err := emailService.VerifyCode(entity.Account, entity.Code)
	if err != nil {
		return nil, err
	}
	if !valid {
		return nil, errors.New("验证码错误")
	}
	// 检查账号是否已存在
	existingUser, err := s.repository.FindByAccount(entity.Account)
	if err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, err
		}
	}
	if existingUser != nil {
		return nil, errors.New("账号已存在")
	}
	// 生成随机 SelfAccount
	SelfAccount := "gin_" + utils.GenerateRandomString(8)
	return s.repository.Create(&model.User{
		Account:     entity.Account,
		Password:    entity.Password,
		SelfAccount: SelfAccount,
	})
}

// Login 用户登录
func (s *userService) Login(account, password string) (*LoginResponse, error) {
	// 通过账号查找用户
	user, err := s.repository.FindByAccount(account)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("账号或密码错误")
		}
		return nil, err
	}

	// 检查用户状态
	if user.UserStatus != model.UserStatusTypeEnable {
		return nil, errors.New("用户已被禁用")
	}

	// 验证密码
	if !crypto.CheckPasswordHash(password, user.Password) {
		return nil, errors.New("账号或密码错误")
	}

	// 生成JWT token
	tokens, err := jwt.GenerateTokens(user)
	if err != nil {
		return nil, err
	}

	return &LoginResponse{
		AccessToken:  tokens.AccessToken,
		RefreshToken: tokens.RefreshToken, // 刷新令牌可以为空
		TokenType:    tokens.TokenType,
	}, nil
}

// RefreshToken 刷新token
func (s *userService) RefreshToken(refreshToken string) (*LoginResponse, error) {

	// 解析refresh token
	claims, err := jwt.ParseRefreshToken(refreshToken)
	if err != nil {
		return nil, err
	}

	// 根据用户ID获取用户信息
	user, err := s.GetUserByID(claims.ID)
	if err != nil {
		return nil, err
	}

	// 生成新的双token
	newTokens, err := jwt.GenerateTokens(user)
	if err != nil {
		return nil, err
	}

	// 返回新的token
	return &LoginResponse{
		AccessToken:  newTokens.AccessToken,
		RefreshToken: newTokens.RefreshToken,
		TokenType:    newTokens.TokenType,
	}, nil
}
